package com.liu.webstore.controller;

import com.liu.webstore.common.Constant;
import com.liu.webstore.entity.Event;
import com.liu.webstore.entity.Page;
import com.liu.webstore.entity.User;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.event.EventProducer;
import com.liu.webstore.service.FollowService;
import com.liu.webstore.service.UserService;
import com.liu.webstore.util.HostHolder;
import com.liu.webstore.util.WebstoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/8/7 10:06
 */
@Controller
public class FollowController {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private FollowService followService;

    @Autowired
    private UserService userService;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 异步请求，加上ResponseBody
     */
    @PostMapping("/follow")
    @ResponseBody
    public String follow(int entityType, int entityId) {
        // todo 没登录则做个拦截器检查，跳转登录页面
        int userId = hostHolder.getUser().getId();
        followService.follow(userId, entityType, entityId);
        // 触发关注事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                // 目前只能关注人
                .setEntityUserId(entityId);
        eventProducer.fireEvent(event);
        return WebstoreUtil.getJsonString(200, "已关注！");
    }

    /**
     * 异步请求，加上ResponseBody
     */
    @PostMapping("/unfollow")
    @ResponseBody
    public String unfollow(int entityType, int entityId) {
        int userId = hostHolder.getUser().getId();
        followService.unFollow(userId, entityType, entityId);
        return WebstoreUtil.getJsonString(200, "已取消关注！");
    }

    @GetMapping("/followeeList/{userId}")
    public String getFolloweeList(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.getUserById(userId);
        if (Objects.isNull(user)) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);
        page.setLimit(5);
        page.setPath("/followeeList/" + userId);
        page.setRows((int) followService.findFolloweeCount(userId, StatusEnum.ENTITY_TYPE_USER.getStatus()));
        List<Map<String, Object>> followeeList = followService.findFolloweeList(userId, page.getOffert(), page.getLimit());
        if (Objects.nonNull(followeeList)) {
            for (Map<String, Object> map : followeeList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", followeeList);
        return "site/followee";
    }

    @GetMapping("/followerList/{userId}")
    public String getFollowerList(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.getUserById(userId);
        if (Objects.isNull(user)) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);
        page.setLimit(5);
        page.setPath("/followerList/" + userId);
        page.setRows((int) followService.findFollowerCount(StatusEnum.ENTITY_TYPE_USER.getStatus(), userId));
        List<Map<String, Object>> followerList = followService.findFollowerList(userId, page.getOffert(), page.getLimit());
        if (Objects.nonNull(followerList)) {
            for (Map<String, Object> map : followerList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", followerList);
        return "site/follower";
    }

    private boolean hasFollowed(int userId) {
        if (Objects.isNull(hostHolder.getUser())) {
            return false;
        }
        return followService.hasFollowed(hostHolder.getUser().getId(), StatusEnum.ENTITY_TYPE_USER.getStatus(), userId);
    }
}
